<?php

class IShanSongSvc
{
    const API_URL = 'http://open.s.bingex.com/openapi';
    const PARTNER_NO = '1000'; //合作伙伴编号

    const STORE_ID = 'MT1001'; //商户唯一id 由闪送分配
    const STORE_NAME = '快方送药'; //商户名称
    const STORE_MOBILE = '15834941000'; //下单人手机号码

    const SIGN_KEY = "12345abcde"; //加密算法key 由闪送提供

    /*
        闪送平台：
        地址：http://www.ishansong.com/bd
        账号：kfyaoapp@163.com
        密码：Kf123456
    */


    /*
        生成签名加密算法
        params
            orderNo 订单编号
    */
    public static function generateSign($orderNo = '') {
        $signStr = sprintf("%s%s%s%s", self::PARTNER_NO, $orderNo, self::STORE_MOBILE, self::SIGN_KEY);

        return strtoupper(md5($signStr));
    }

    /*
        获取闪送商户信息
    */
    public function getMerchantInfo()
    {
        $data = array();
        $data['id'] = self::STORE_ID;
        $data['mobile'] = self::STORE_MOBILE;
        $data['name'] = self::STORE_NAME;
        $data['token'] = NULL;

        return $data;
    }

    /*
        生成商户信息
        params
            mobile 寄件人手机号码
            name 寄件人姓名
            city 城市名称
            addr 地址
            addrDetail 详细地址信息
            lng 经度 116.314423 百度坐标
            lat 维度 40.042802
    */
    public function createSenderInfo($mobile = '', $name = '', $city = '', $addr = '', $addrDetail = '', $lng = '', $lat = '')
    {
        $data = array();
        $data['mobile'] = $mobile;
        $data['name'] = $name;
        $data['city'] = $city;
        $data['addr'] = $addr;
        $data['addrDetail'] = $addrDetail;
        $data['lng'] = $lng;
        $data['lat'] = $lat;

        return $data;
    }

    /*
        生成客户信息
        params
            mobile 收件人手机号码
            name 收件人姓名
            city 城市名称
            addr 地址
            addrDetail 详细地址信息
            lng 经度 116.314423 百度坐标
            lat 维度 40.042802
    */
    public function createReceiverInfo($mobile = '', $name = '', $city = '', $addr = '', $addrDetail = '', $lng = '', $lat = '')
    {
        $data = array();
        $data['mobile'] = $mobile;
        $data['name'] = $name;
        $data['city'] = $city;
        $data['addr'] = $addr;
        $data['addrDetail'] = $addrDetail;
        $data['lng'] = $lng;
        $data['lat'] = $lat;

        return $data;
    }

    /*
        创建订单信息
        parmas
            order_id 订单id
            product_name 商品名称
            addition 加价费用 单位 分 不加价为0
            remark 备注信息 最长250个字符

            merchant_info 闪送商户信息
            sender_info 门店信息
            receiver_info 客户信息
    */
    public function createOrder($order_id = '', $product_name = '', $addition = 0, $remark = '', $merchant_info = array(), $sender_info = array(), $receiver_info = array())
    {
        $data = array();
        $data['orderNo'] = $order_id;
        $data['goods'] = $product_name;
        $data['weight'] = 1;
        $data['addition'] = $addition;
        $data['remark'] = $remark;

        $data['merchant'] = $merchant_info;
        $data['sender'] = $sender_info;
        $data['receiverList'] = array($receiver_info); //收件人列表  目前支持一个收件人

        return $data;
    }

    /*
        订单状态查询
        parmas
            order_id 合作伙伴订单编号
            is_sorder_no 闪送平台订单号
    */
    public function getOrderInfo($order_id = '', $is_sorder_no = '')
    {
        $data = array();
        $data['orderno'] = $order_id;
        $data['mobile'] = self::STORE_MOBILE;
        $data['issorderno'] = $is_sorder_no;

        return $data;
    }

    /*
        取消订单
        parmas
            order_id 合作伙伴订单编号
            is_sorder_no 闪送平台手机号
    */
    public function cancelOrder($order_id = '', $is_sorder_no = '')
    {
        $data = array();
        $data['orderno'] = $order_id;
        $data['mobile'] = self::STORE_MOBILE;
        $data['issorderno'] = $is_sorder_no;

        return $data;
    }

    /*
        计算费用
        params
            order_info 订单详情对象(createOrder)
    */
    public function getAmonutByIShanSong($order_info = array())
    {
        $this->DLOG("get_amount : " . json_encode($order_info), "run", "ishansong_order");

        $url =self::API_URL."/order/v2/calc";

        $data = array();
        $data['partnerNo'] = self::PARTNER_NO;
        $data['signature'] = $this->generateSign($order_info['orderNo']);
        $data['order'] = $order_info;

        $postData = json_encode($data);

        $res = json_decode(self::doPost($url, $postData), true);

        $log = array(
            "orderNo" => $data['order_info']['orderNo'],
            "res" => $res
        );
        $this->DLOG("get_amount_res : " . json_encode($log), "run", "ishansong_order");
        return $res;
    }

    /*
        下单
        params
            order_info 订单详情对象(createOrder)
    */
    public function sendOrderToIShanSong($order_info = array())
    {
        $this->DLOG("send_order : " . json_encode($order_info), "run", "ishansong_order");

        $url =self::API_URL."/order/v2/save";

        $data = array();
        $data['partnerNo'] = self::PARTNER_NO;
        $data['signature'] = $this->generateSign($order_info['orderNo']);
        $data['order'] = $order_info;

        $postData = json_encode($data);

        $res = json_decode(self::doPost($url, $postData), true);

        $log = array(
            "orderNo" => $data['orderno'],
            "res" => $res
        );
        $this->DLOG("send_order : " . json_encode($log), "run", "ishansong_order");
        return $res;
    }

    /*
        查询闪送订单状态
        params
            data 订单状态数据对象(getOrderInfo)
    */
    public function getOrderInfoByIShanSong($data = array())
    {
        $this->DLOG("order_info : " . json_encode($data), "run", "ishansong_order");

        $url =self::API_URL."/order/v2/info";

        $getData = array();
        $getData['partnerno'] = self::PARTNER_NO;
        $getData['signature'] = $this->generateSign($data['orderno']);
        $getData = array_merge($getData, $data);


        $res = json_decode(self::doGet($url, $getData), true);

        $log = array(
            "orderNo" => $data['orderno'],
            "res" => $res
        );
        $this->DLOG("order_info : " . json_encode($log), "run", "ishansong_order");
        return $res;
    }

    /*
        取消闪送订单
        params
            data 订单状态数据对象(cancelOrder)
    */
    public function cancelOrderToIShanSong($data = array())
    {
        $this->DLOG("cancel_order : " . json_encode($data), "run", "ishansong_order");

        $url =self::API_URL."/order/v2/cancel";

        $getData = array();
        $getData['partnerno'] = self::PARTNER_NO;
        $getData['signature'] = $this->generateSign($data['orderno']);
        $getData = array_merge($getData, $data);


        $res = json_decode(self::doGet($url, $getData), true);

        $log = array(
            "orderNo" => $data['order_info']['orderNo'],
            "res" => $res
        );
        $this->DLOG("cancel_order : " . json_encode($log), "run", "ishansong_order");
        return $res;
    }

    public function DLOG($log_content='', $log_level='', $log_name='')
    { 

        if(empty($log_level)||empty($log_content))
            return;
        
        
        if(empty($log_name) && $log_level == 'run')
            $log_name = 'run';

        $log_dir = "/mnt/logs/";
        $log_file = $log_dir.$log_name.".".date('Y-m-d').".log";
        
        //默认每行日志必写的内容，统一在这里处理
        // ZHANGXI 2015/1/7 for regular
        $time = sprintf("%8s.%03d",date('H:i:s'),floor(microtime()*1000));
        //$time = date('H:i:s').".".floor(microtime()*1000);
        $ip = sprintf("%15s",$_SERVER["REMOTE_ADDR"]);

        $id =   "req-Fn";

        $path_arr = explode("/", $_SERVER['REQUEST_URI']);

        $content_prefix = "[ ".$time." ".$ip." ".$id." ".$log_level." ".$path_arr[1]." ".$path_arr[2]." ] ";

        $fp = fopen($log_file, 'a+');
        fwrite($fp, $content_prefix.$log_content." [".getmypid()."]\n");
        fclose($fp);
        return true;
    }

    public static function doPost($url, $param, $method = "POST")
    {
        // echo 'Request url is ' . $url . PHP_EOL;
        if (empty($url) or empty($param)) {
            throw new InvalidArgumentException('Params is not of the expected type');
        }

        // 验证url合法性
//        if (!filter_var($url, FILTER_VALIDATE_URL)) {
//            throw new InvalidArgumentException('Url is not valid');
//        }

        if (!empty($param) and is_array($param)) {
            $param = urldecode(json_encode($param));
        } else {
            // $param = urldecode(strval($param));
            $param = strval($param);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证

        if (strcmp($method, "POST") == 0) {  // POST 操作
            curl_setopt($ch, CURLOPT_POST, true);
        } else if (strcmp($method, "DELETE") == 0) { // DELETE操作
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        } else {
            throw new InvalidArgumentException('Please input correct http method, such as POST or DELETE');
        }

        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: Application/json'));
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (!empty($result) and $code == '200') {
            return $result;
        }
        return false;
    }





    public static function doGet($url, $param = null)
    {
        if (empty($url) or (!empty($param) and !is_array($param))) {
            throw new InvalidArgumentException('Params is not of the expected type');
        }
        // 验证url合法性
//        if (!filter_var($url, FILTER_VALIDATE_URL)) {
//            throw new InvalidArgumentException('Url is not valid');
//        }

        if (!empty($param)) {
            $url = trim($url, '?') . '?' . http_build_query($param);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if (!empty($result) and $code == 200) {
            return $result;
        }
        return false;
    }
}